package h0909;

import java.util.Arrays;

/**
 * @author 不知名帅哥
 * @version 1.0
 * @description 最接近的三数之和
 * @date 2024/9/9 21:56
 */
public class ClosestThreeNumSum {
    public static void main(String[] args) {

    }

    public int threeSumClosest(int[] nums, int target) {
        int min = Integer.MAX_VALUE / 2;
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            int left = i + 1;
            int right = nums.length - 1;
            while (left < right) {
                int a = nums[i] + nums[left] + nums[right];
                if (a == target) {
                    return target;
                } else if (Math.abs(a - target) < Math.abs(min - target)) {
                    min = a;
                }
                if (a > target) {
                    right--;
                }
                if (a < target) {
                    left++;
                }
            }
        }
        return min;
    }
}
